import os
from pathlib import Path

from docx import Document
from openpyxl.reader.excel import load_workbook

from base.RAG_da_bang.re_utils import re_anonymize_all



def scan_cells_with_names(file_path):
    """读取Excel文件并打印所有单元格的名称和值"""
    wb = load_workbook(filename=file_path)
    bool_flag = False
    for sheet_name in wb.sheetnames:
        ws = wb[sheet_name]
        for row in ws.iter_rows():
            for cell in row:
                # 获取单元格坐标（如A1、B3等）
                cell_name = cell.coordinate
                # 获取单元格值
                cell_value = cell.value
                if cell_value:
                    re_text = re_anonymize_all(str(cell_value))
                    if str(cell_value) != re_text:
                        # print('有敏感信息')
                        print(sheet_name, ": ", cell_name, ": ", cell_value)
                        bool_flag = True
                        cell.value = re_text
    if bool_flag:
        wb.save('hb.xlsx')


def scan_files(root_dir, extensions=None, max_depth=None):
    """
    递归扫描多层子目录中的文件
    :param root_dir: 根目录路径
    :param extensions: 允许的文件扩展名列表(如['.txt', '.csv'])，None表示所有文件
    :param max_depth: 最大扫描深度，None表示无限制
    :return: 文件路径生成器
    """
    root_path = Path(root_dir)
    if not root_path.exists():
        raise FileNotFoundError(f"目录不存在: {root_dir}")

    for item in root_path.rglob('*'):
        if not item.is_file():
            continue

        # 检查文件扩展名
        if extensions and item.suffix.lower() not in [ext.lower() for ext in extensions]:
            continue

        # 检查目录深度
        if max_depth is not None:
            depth = len(item.relative_to(root_path).parts) - 1
            if depth > max_depth:
                continue
        yield item.absolute()



if __name__ == '__main__':
    try:
        dir_path = r'D:\工作\IT公司RAG打榜比赛营销相关数据需求\china_mobile_docs'
        exts = '.xls'
        extensions = [ext.strip() for ext in exts.split(',')] if exts else None
        print(extensions)

        print("\n扫描结果:")
        # for idx, file in enumerate(scan_files(dir_path, extensions, max_depth=5), 1):
        #     print(f"{idx:>4}. {file}")
            # try:
            #     # read_cells_with_names(file)
            #     scan_cells_with_names(file)
            # except Exception as e:
            #     print(f"错误: {e}")
        # scan_cells_with_names(r'hb0312.xlsx')
    except Exception as e:
        print(f"错误: {e}")
